package com.dlgcy.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import weibo4j.Oauth;
import weibo4j.model.WeiboException;

import com.dlgcy.xinlang_weibo.OAuth4Code;

public class AuthorizeFrame extends JFrame {
	JTextArea hint1, hint2;
	JLabel picHint, inputHint;
	JTextField input;
	JButton sure;
	JPanel inputPanel, wholePanel;
	ImageIcon img = new ImageIcon("image/hint_xl.png");
	Oauth oauth = null;

	public AuthorizeFrame() {
		wholePanel = new JPanel();
		wholePanel.setSize(740, 700);
		wholePanel.setLayout(new BoxLayout(wholePanel, BoxLayout.Y_AXIS));
		hint1 = new JTextArea("已在您的默认浏览器中打开授权页面，请在该页面进行授权，谢谢！");
		hint2 = new JTextArea("授权完成后请不要关闭跳转页面（百度首页），并请留意该页地址栏，以便获取相关验证信息。");
		picHint = new JLabel(img);

		inputPanel = new JPanel();
		inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.X_AXIS));
		inputHint = new JLabel("验证信息(Ctrl+V 粘贴)：");
		input = new JTextField();
		inputPanel.add(inputHint);
		inputPanel.add(input);
		sure = new JButton("确认");

		wholePanel.add(hint1);
		wholePanel.add(hint2);
		wholePanel.add(picHint);
		wholePanel.add(inputPanel);
		wholePanel.add(sure);

		try {
			oauth = OAuth4Code.authorize(); // 新浪微博授权；
		} catch (WeiboException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		sure.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				String str = input.getText();
				Boolean isDone = OAuth4Code.isAuthorized(oauth, str);
				if (isDone) {
					JOptionPane.showMessageDialog(wholePanel, new JLabel("授权成功！请重启软件。"), "授权", JOptionPane.INFORMATION_MESSAGE);
				} else {
					JOptionPane.showMessageDialog(wholePanel, new JLabel("授权失败！请重新授权。"), "授权", JOptionPane.ERROR_MESSAGE);
				}
				dispose();
			}
		});
		showMe();
	}

	public void showMe() {
		this.add(wholePanel);
		pack(); // 自动设置大小；
		// authorizeFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLocation(300, 10);
		setVisible(true);
	}

}
